<?php
/**
 * Web user class file
 */
 
/**
 * WebUser class of the User Module
 * 
 * @package Auth
 */
class WebUser extends CWebUser {
    	
	/**
	 * return the role of the current user
	 */
    public function getRole() {
        return $this->getState('__role');
    }
    
    /**
	 * return the id of the current user
	 */
    public function getId() {
        return $this->getState('__id') ? $this->getState('__id') : 0;
    }

//    protected function beforeLogin($id, $states, $fromCookie)
//    {
//        parent::beforeLogin($id, $states, $fromCookie);
//
//        $model = new UserLoginStats();
//        $model->attributes = array(
//            'user_id' => $id,
//            'ip' => ip2long(Yii::app()->request->getUserHostAddress())
//        );
//        $model->save();
//
//        return true;
//    }

    /**
	 * after login hook to call update session
	 * @param fromCookie $string
	 */
	protected function afterLogin($fromCookie) {
        parent::afterLogin($fromCookie);
        $this->updateSession();
	}

    /**
	 * add the profile to the session
	 */
    public function updateSession() {
        $user = Yii::app()->getModule('user')->user($this->id);
        $userAttributes = CMap::mergeArray(array(
	            'email'=>$user->email,
	            'username'=>$user->username,
	            'create_at'=>$user->create_at,
	            'lastvisit_at'=>$user->lastvisit_at,
	       ),$user->profile->getAttributes());
        foreach ($userAttributes as $attrName=>$attrValue) {
            $this->setState($attrName,$attrValue);
        }
    }

    /**
	 * Return safe user data.
	 */
    public function model($id=0) {
        return Yii::app()->getModule('user')->user($id);
    }

	/**
	 * Return safe user data.
	 */
    public function user($id=0) {
        return $this->model($id);
    }

    /**
	 * return a user model given username
	 */
    public function getUserByName($username) {
        return Yii::app()->getModule('user')->getUserByName($username);
    }

	/**
	 * Return the admin users
	 */
    public function getAdmins() {
        return Yii::app()->getModule('user')->getAdmins();
    }

    /**
	 * check if the user is an admin
	 */
    public function isAdmin() {
        return Yii::app()->getModule('user')->isAdmin();
    }
}